package userserv

import (
	"codedef"
	"encoding/json"
	"github.com/garyburd/redigo/redis"
	"log"
	"net/http"
	"rhelper"
	"strings"
)

func objCountOfSplitString(str string, split string) int {
	if str == "" {
		return 0
	}

	if !strings.Contains(str, split) {
		return 1
	}

	strArray := strings.Split(str, split)
	return len(strArray)
}

func onLoadMain(w http.ResponseWriter, r *http.Request) {
	account := r.Header.Get("account")

	conn := rhelper.Pool().Get()
	defer conn.Close()

	type farm struct {
		Id        string `json:"id"`
		Name      string `json:"name,omitempty"`
		TaskCount int    `json:"taskcount"`
		PlanCount int    `json:"plancount"`
	}

	type main_s struct {
		Farms []farm `json:"farms"`
	}

	main := main_s{}

	// load all farms
	farmsString, err := redis.String(conn.Do("HGET", rhelper.AccountHash+account, "farms"))
	if err != nil {
		log.Println(err)
		w.WriteHeader(200)
		return
	}

	if farmsString == "" {
		w.WriteHeader(200)
		return
	}

	farmsStrArray := strings.Split(farmsString, ",")
	farmArray := make([]farm, len(farmsStrArray))
	var index int = 0

	for _, farmStr := range farmsStrArray {
		if farmStr == "" {
			continue
		}

		fields, err := redis.Strings(conn.Do("HMGET", rhelper.FarmHash+farmStr, "name", "tasks", "plan"))
		if err != nil {
			log.Println(err)
			continue
		}

		if len(fields[0]) < 1 {
			continue
		}

		f := farm{}
		f.Id = farmStr
		f.Name = fields[0]
		f.TaskCount = objCountOfSplitString(fields[1], ",")
		f.PlanCount = objCountOfSplitString(fields[2], ",")

		farmArray[index] = f
		index++
	}

	farmArray = farmArray[0:index]
	main.Farms = farmArray

	buf, err := json.Marshal(main)
	if err != nil {
		log.Println(err)
		replyError(w, codedef.ERR_ENCODE)
		return
	}

	w.Write(buf)
}

func init() {
	myMux.muxHandlers.HandleFunc("/loadMain", onLoadMain)
}
